package com.itheima.practice.config;


import com.itheima.practice.constants.SystemConstants;
import com.itheima.practice.tool.PackageLookupTool;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ai.openai.OpenAiChatModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class CommonConfig {

    @Bean
    //这个参数用于注入IOC容器中的对象，体现了面向接口编程的思想，使用的是openai实现
    public ChatClient servicechatClient(OpenAiChatModel chatModel, ChatMemory chatMemory, PackageLookupTool tool) {
        //如果想调用openAi的大模型，这里参数就传入openAi的模型对象
        return ChatClient.builder(chatModel) // 创建ChatClient工厂
                // 设置系统角色 给他个背景
                .defaultSystem(SystemConstants.CUSTOMER_SERVICE_SYSTEM)
                // 添加默认的Advisor,记录日志
                .defaultAdvisors(new SimpleLoggerAdvisor())
                //管理聊天记录
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .defaultTools(tool)
                .build();// 构建ChatClient实例
    }

    /**
     * 使用内存的记忆存储功能
     * @return
     */
    @Bean
    public ChatMemory chatMemory() {
        // 使用Map作为简单的内存聊天历史存储
        return new ChatMemory() {
            private final Map<String, List<Message>> memory = new HashMap<>();
            
            @Override
            public void add(String conversationId, List<Message> messages) {
                memory.computeIfAbsent(conversationId, k -> new ArrayList<>()).addAll(messages);
            }
            
            @Override
            public List<Message> get(String conversationId) {
                return memory.getOrDefault(conversationId, new ArrayList<>());
            }
            
            @Override
            public void clear(String conversationId) {
                memory.remove(conversationId);
            }
        };
    }
}